package com.tanhua.dubbo.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.enums.IdType;
import com.tanhua.dubbo.pojo.FollowUser;
import com.tanhua.dubbo.pojo.Video;
import com.tanhua.dubbo.service.IdService;
import com.tanhua.dubbo.vo.PageInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.ArrayList;
import java.util.List;

@DubboService(version = "1.0.0")
public class VideoApiImpl implements VideoApi {

    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 保存小视频
     *
     * @param video
     * @return 保存成功后，返回视频id
     */
    @Override
    public String saveVideo(Video video) {
        //校验
        if (!ObjectUtil.isAllNotEmpty(video.getUserId(),
                video.getPicUrl(), video.getVideoUrl())) {
            return null;
        }

        video.setId(ObjectId.get());
        video.setCreated(System.currentTimeMillis());
        video.setVid(this.idService.createId(IdType.VIDEO));
        video.setSeeType(1);

        this.mongoTemplate.save(video);

        return video.getId().toHexString();
    }

    /**
     * 查询小视频列表
     * 实现：优先查询推荐的小视频列表的数据，其次按照时间倒序排序查询MongoDB中的数据
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(new ArrayList<>());

        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        String redisValue = this.redisTemplate.opsForValue().get(redisKey);
        List<String> vidStrList = StrUtil.split(redisValue, ',');
        List<Long> vidList = new ArrayList<>();
        if (CollUtil.isNotEmpty(vidStrList)) {
            //手动分页
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int start = startEnd[0]; //开始下标
            int end = Math.min(vidStrList.size(), startEnd[1]); // 结束下标

            for (int i = start; i < end; i++) {
                vidList.add(Convert.toLong(vidStrList.get(i)));
            }
        }

        if (CollUtil.isEmpty(vidList)) {
            //TODO 排除已经在推荐列表中返回的视频数据
            //没有推荐数据 或 推荐数据已经查完了
            //计算前面推荐数据的页数
            int totalPage = PageUtil.totalPage(vidStrList.size(), pageSize);

            PageRequest pageRequest = PageRequest.of(page - totalPage - 1, pageSize,
                    Sort.by(Sort.Order.desc("created")));
            Query query = new Query().with(pageRequest);
            List<Video> videoList = this.mongoTemplate.find(query, Video.class);
            pageInfo.setRecords(videoList);
        } else {
            Query query = Query.query(Criteria.where("vid").in(vidList));
            List<Video> videoList = this.mongoTemplate.find(query, Video.class);

            //按照推荐顺序进行排序
            for (Long vid : vidList) {
                for (Video video : videoList) {
                    if (ObjectUtil.equal(vid, video.getVid())) {
                        pageInfo.getRecords().add(video);
                        break;
                    }
                }
            }
        }

        return pageInfo;
    }

    /**
     * 根据id查询小视频
     *
     * @param videoId
     * @return
     */
    @Override
    public Video queryVideoById(String videoId) {
        return this.mongoTemplate.findById(new ObjectId(videoId), Video.class);
    }

    /**
     * 关注用户
     *
     * @param userId       当前用户
     * @param followUserId 关注的目标用户
     * @return
     */
    @Override
    public Boolean followUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }
        try {
            FollowUser followUser = new FollowUser();
            followUser.setId(ObjectId.get());
            followUser.setUserId(userId);
            followUser.setCreated(System.currentTimeMillis());
            followUser.setFollowUserId(followUserId);
            this.mongoTemplate.save(followUser);
            //将数据存到redis
            String redisKey = this.getCommentRedisKey(userId);
            String hashKey = String.valueOf(followUserId);
            this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 取消关注
     *
     * @param userId       当前用户
     * @param followUserId 关注的目标用户
     * @return
     */
    @Override
    public Boolean disFollowUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }
        //判断改用户是否关注
        if (!this.isFollowUser(userId, followUserId)) {
            return false;
        }
        //删除mongoDB数据
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId));
        DeleteResult result = this.mongoTemplate.remove(query, FollowUser.class);
        //删除redis中数据
        if (result.getDeletedCount() > 0) {
            String redisKey = this.getCommentRedisKey(userId);
            String hashKey = String.valueOf(followUserId);
            this.redisTemplate.opsForHash().delete(redisKey, hashKey);
            return true;
        }
        return false;
    }

    /**
     * 查询用户是否关注某个用户
     *
     * @param userId       当前用户
     * @param followUserId 关注的目标用户
     * @return
     */
    @Override
    public Boolean isFollowUser(Long userId, Long followUserId) {
        String redisKey = this.getCommentRedisKey(userId);
        String hashKey = String.valueOf(followUserId);
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

    private String getCommentRedisKey(Long userId) {
        return VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
    }
}
